import java.util.*;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2022-10-05
 * Time:22:29
 */

/**
 * 力扣811:子域名访问计数
 */

public class subdomainVisits {
    public static void main(String[] args) {
        String[] cpdomains = {"9001 discuss.leetcode.com"};
        System.out.println(subdomainVisits(cpdomains));
    }

    //cpdomains = ["9001 discuss.leetcode.com"]
    //输出：["9001 leetcode.com","9001 discuss.leetcode.com","9001 com"]

    public static List<String> subdomainVisits(String[] cpdomains) {
        List<String> ans = new ArrayList<>();
        Map<String, Integer> counts = new HashMap<>();
        for (String cpdomain : cpdomains) {
            //indexOf()索引 ' ' 所在的位置(下标)   4
            int space = cpdomain.indexOf(' ');

            //这里的substring()方法截取的字符串是从索引0开始的，到space
            //Integer.parseInt() 将String类型的转化为整数
            int count = Integer.parseInt(cpdomain.substring(0, space));      //9001

            //这里的substring()方法截取的字符串是从索引space开始的，到尾
            String domain = cpdomain.substring(space + 1);       //discuss.leetcode.com

            //V getOrDefault(Object key, V defaultValue) 返回 key 对应的 value，key 不存在，返回默认值
            counts.put(domain, counts.getOrDefault(domain, 0) + count);
                                                 //discuss.leetcode.com  //9001
                               //discuss.leetcode.com
            for (int i = 0; i < domain.length(); i++) {
                if (domain.charAt(i) == '.') {
                    String subdomain = domain.substring(i + 1);
                    counts.put(subdomain, counts.getOrDefault(subdomain, 0) + count);
                }
            }
        }
        for (Map.Entry<String, Integer> entry : counts.entrySet()) {
            String subdomain = entry.getKey();
            int count = entry.getValue();
            ans.add(count + " " + subdomain);
        }
        return ans;
    }
}
